<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use http\Env\Response;
use Illuminate\Http\Request;
use App\Http\Requests\RegisterAuthRequest;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\JWT;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public $loginAfterSignUp = true;

    public function register(RegisterAuthRequest $request) {
        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
        $user->save();

        if ($this->loginAfterSignUp) {
            return $this->login($request);
        }

        return response()->json([
            'code'   => 200,
            'data'      => $user
        ]);
    }

    public function login(Request $request) {
        // $input = $request->only('username', 'password');
        $jwt_token = null;
        $input = ['name' => $request->username, 'password' => $request->password];
        if (!$jwt_token = JWTAuth::attempt($input)) {
            return response()->json([
                'code'   => 201,
                'message'   => 'Invalid Email  or password'
            ]);
        }

        return response()->json([
            'code'   => 200,
            'data'   => ['token' => $jwt_token]
        ]);
    }

    public function logout(Request $request) {
        $request->offsetSet('token', $request->header('X-Token'));
        $this->validate($request, ['token' => 'required']);

        try {
            JWTAuth::setToken($request->token)->invalidate();
            return response()->json([
                'code'   => 200,
                'message'   => 'user logged out successfully'
            ]);
        } catch (JWTException $exception) {
            return response()->json([
                'code'   => 202,
                'message'   => 'Sorry, the user cannot be logged out:' . $exception->getMessage()
            ]);
        }
    }

    public function getAuthUser(Request $request) {
        $this->validate($request,  ['token' => 'required']);
        $token  = $request->token;
        $user   = JWTAuth::setToken($token)->toUser();
        $user->roles = ["admin"];
        $user->introduction = "";
        $user->avatar = $user->profile_photo_url;
        return response()->json([
            'code'  => 200,
            'data'  => $user
        ]);
    }
}
